package com.zilue.security.util.base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * Created by zilue on 2016/8/10.
 */
public class Base64Util {
//    public static Logger logger = LoggerFactory.getLogger(Base64Util.class);
    private static BASE64Encoder base64Encoder;
    private static BASE64Decoder base64Decoder;
    static {
        base64Encoder=new BASE64Encoder();
        base64Decoder=new BASE64Decoder();
    }

    /**
     * BASE64编码
     *
     * @param content
     * @return
     */
    public static String encodeString(String content) {
        if (content == null) return null;
        String encode = base64Encoder.encode(content.getBytes());
        encode=encode.replaceAll("[\\s*\t\n\r]", "");
        return encode;
    }

    /**
     * BASE64解码
     *
     * @param content
     * @return
     */
    public static String decodeString(String content) {
        if (content == null) return null;
        try {
            return new String(base64Decoder.decodeBuffer(content));
        } catch (IOException e) {
//            logger.error("base64解码失败", e);
            return null;
        }
    }

    /**
     * BASE64编码（byte）
     *
     * @param content
     * @return
     */
    public static String encodeByte(byte[] content) {
        if (content == null) return null;
        String encode = base64Encoder.encode(content);
        encode=encode.replaceAll("[\\s*\t\n\r]", "");
        return encode;
    }

    /**
     * BASE64解码（byte）
     *
     * @param content
     * @return
     */
    public static byte[] decodeByte(String content) {
        if (content == null) return null;
        try {
            return base64Decoder.decodeBuffer(content);

        } catch (IOException e) {
//            logger.error("base64解码失败",e);
            return null;
        }
    }

    public static void main(String[] args) {
        String s = encodeString("Connected to the target VM, address: '127.0.0.1:53115', transport: 'socket'");
        System.out.println(s);
    }

}
